#include "musiclist.h"
#include <QMimeDatabase>
#include <QDebug>
#include <QSqlQuery>

MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{  
    for (auto musicUrl : urls)
    {
        // 先过滤重复的
        QString musicPath = musicUrl.toLocalFile();
        if (musicPaths.contains(musicPath))
        {
            continue;
        }

        // 没加载过,加入
        musicPaths.insert(musicPath);
        // 不一定是歌曲，再次筛选
        QMimeDatabase mimeDB;
        QMimeType mimeType = mimeDB.mimeTypeForFile(musicUrl.toLocalFile());
        QString mime = mimeType.name();
        if ( mime == "audio/mpeg" || mime == "audio/flac" || mime == "audio/wav")
        {
            // url转化为music对象，添加进去
            Music music(musicUrl);
            musicList.push_back(music);
        }
    }
}

MusicList::iteraor MusicList::begin()
{
    return musicList.begin();
}

MusicList::iteraor MusicList::end()
{
    return musicList.end();
}

MusicList::iteraor MusicList::findMusicByMusicId(const QString &musicId)
{
    for (iteraor it = begin(); it != end(); it++)
    {
        if (it->getMusicId() == musicId)
        {
            return it;
        }
    }

    return end();
}

void MusicList::writeToDB()
{
    // 遍历列表插入数据
    for (auto music : musicList)
    {
        music.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql = ("SELECT musicId, musicName, musicSinger, musicAlbum,\
                 duration, musicUrl, isLike, isHistory FROM musicInfo");
    QSqlQuery query;
    if (!query.exec(sql))
    {
        qDebug() << "数据库查询失败";
        return;
    }

    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        // music.setMusicUrl("file:///" + query.value(5).toString());
        music.setMusicUrl(query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        musicList.push_back(music);
        musicPaths.insert(query.value(5).toString());
    }
}
